<template>
  <div class="add-box">
    <el-form :model="form" class="my-form" label-width="140px" :disabled="disabled">
      <el-form-item label="基础信息" class="form-title"></el-form-item>
      <el-form-item label="商家名称" required>
        <el-input clearable v-model="form.client_name" style="width: 300px;" maxlength="50"
          placeholder="输入商家名称，需与合同主体名称一致" />
      </el-form-item>
      <el-form-item label="商家简称" required>
        <el-input clearable v-model="form.short_name" style="width: 300px;" maxlength="50"
          placeholder="输入商家简称，主要用于系统显示" />
      </el-form-item>
      <el-form-item label="所属国家" required>
        <el-select clearable v-model="form.belong_country" placeholder="请选择所属国家" style="width: 145px;">
          <el-option :label="item" :value="index" v-for="(item, index) in countryList" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" required>
        <el-input clearable v-model="form.contacts" style="width: 300px;" maxlength="30" placeholder="输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" required>
        <el-select v-model="form.telephone_prefix" style="width: 110px;margin-right: 10px;">
          <el-option v-for="(item, index) in prefixList" :key="index" :label="item + ' ' + index" :value="index" />
        </el-select>
        <el-input clearable v-model="form.telephone" :formatter="(v) => v.trim()" style="width: 300px;" maxlength="11"
          placeholder="输入联系电话" />
      </el-form-item>
      <el-form-item label="联系邮箱" required>
        <el-input clearable v-model="form.client_email" :formatter="(v) => v.trim()" style="width: 300px;" maxlength="50"
          placeholder="输入商家联系邮箱" />
      </el-form-item>
      <el-form-item label="联系地址" required>
        <el-input clearable v-model="form.address" style="width: 300px;" maxlength="50" placeholder="输入商家联系地址" />
      </el-form-item>
      <el-divider />
      <el-form-item label="管理员信息" class="form-title"></el-form-item>
      <el-form-item label="管理员名称" required>
        <el-input clearable v-model="form.user_name" style="width: 300px;" maxlength="50" placeholder="请输入管理员名称" />
      </el-form-item>
      <el-form-item label="登陆邮箱" required>
        <el-input clearable v-model="form.user_email" :disabled="isEdit" :formatter="(v) => v.trim()"
          style="width: 300px;" maxlength="50" placeholder="请输入商家登录邮箱" />
      </el-form-item>
      <el-form-item label="初始密码" required v-if="!isEdit">
        <el-input clearable type="password" show-password v-model="form.password" :formatter="(v) => v.trim()"
          style="width: 300px;" maxlength="20" placeholder="请输入不少于6位的初始登录密码" />
      </el-form-item>
      <el-divider />
      <el-form-item label="运营设置" class="form-title"></el-form-item>
      <el-form-item label="货币单位" required>
        <el-select clearable :disabled="isEdit" v-model="form.currency_unit" placeholder="请选择货币单位" style="width: 145px;">
          <el-option :label="item.label + ' ' + item.unit_symbol" :value="item.value" v-for="(item, index) in unitList"
            :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item label="POS机预授权金额" required>
        <el-input clearable v-model="form.allow_money" :formatter="(v) => v.trim()" style="width: 300px;" maxlength="12"
          placeholder="请输入金额" />
      </el-form-item>
      <el-divider />
      <el-form-item label="收款设置" class="form-title"></el-form-item>
      <el-form-item label="收款账户" v-if="payee_settings.length > 0">
        <template #default>
          <div v-for="(item, index) in payee_settings" :key="index" style="width: 100%;margin-bottom: 10px;">
            <el-select v-model="payee_settings[index].provider_id" placeholder="选择服务商及收单行"
              style="width: 200px;margin-right: 10px;">
              <el-option v-for="(it, idx) in providerList" :key="idx" :label="it.name" :value="it.id" />
            </el-select>
            <el-input clearable v-model="payee_settings[index].merchant_no" style="width: 200px;margin-right: 10px;"
              maxlength="30" placeholder="请输入商户号ID" />
            <span class="posnum" v-if="item.num > 0" @click.stop="toPOSList(item.pos_sn_no)">
              已关联{{ item.num }}个SN号</span>
            <el-button type="primary" :style="{ width: item.num > 0 ? '100px' : '212px' }"
              @click.stop="toAddPOS(index)">{{ item.num > 0 ? '继续添加' : '添加关联设备POS机SN号' }}</el-button>
            <el-icon class="delete-payee" v-if="payee_settings.length > 1" @click.stop="deletePayee(index)">
              <Delete />
            </el-icon>
          </div>
        </template>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" plain icon="plus" style="width: 632px;" @click.stop="addPayee"> 添加收款账户 </el-button>
      </el-form-item>
    </el-form>
    <el-form-item class="btn-box">
      <el-button @click="back">返回</el-button>
      <el-button type="primary" @click="submitCreate" :disabled="disabled" :loading="isSubmit">{{ isEdit ? '修改' : '提交保存'
      }}</el-button>
    </el-form-item>
    <!-- 新增pos机 -->
    <AddPOSSN ref="addPOSSNRef" @savePOSVal="savePOSVal"></AddPOSSN>
    <!-- 查询pos机 -->
    <QueryPOS ref="queryPOSRef" />
  </div>
</template>
<script setup>
import AddPOSSN from './components/AddPOSSN.vue';
import QueryPOS from './components/QueryPOS.vue';
import { merchantDetail, merchantConfigInit, getProvider, merchantCreated, merchantUpdated, getClientDeviceBySn } from '@/api/merchantManage/merchantManage';
import { onMounted, ref, watchEffect } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElLoading } from 'element-plus';
import { isEmpty } from 'lodash-es';
import { useCommonStore } from '@/stores';

const route = useRoute();
const router = useRouter();
const commonStore = useCommonStore();
const addPOSSNRef = ref(null);
const queryPOSRef = ref(null);
const disabled = ref(false);
const isSubmit = ref(false);
const isEdit = ref(!!route.query.client_no)
const form = ref({
  client_name: '',//商家名称
  short_name: '',//商家简称
  belong_country: '',//所属国家
  contacts: '',//联系人
  telephone: '',//联系电话
  telephone_prefix: '',//区号
  client_email: '',//登录邮箱
  address: '',//联系地址

  user_name: '',//管理员名称
  user_email: '',//管理员邮箱
  password: '',//密码
  user_no: '',//管理员编号，编辑时需要

  currency_unit: '',//货币单位
  allow_money: '',//预授权金额
  payee_settings: []//收款账户
});

const countryList = ref([]);//国家
const unitList = ref([]);//单位
const prefixList = ref([]);//区号
const providerList = ref([]);//服务商

const telReg1 = /^[0-9]{1,4}([-]?[0-9]{1,4})?$/;
const telReg2 = /^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(16[6])|(17[0-9])|(18[0-9])|(19[1|8|9]))\d{8}$/;
const emailReg = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const payee_settings = ref([{}]);
const payee_index = ref(0);
// methods
const submitCreate = () => {
  if (!rules()) {
    return false;
  }
  isSubmit.value = true;
  initPayee();
  if (isEdit.value) {
    updateMerchant()
  } else {
    createMerchant()
  }

}

// 表单校验
const rules = () => {
  if (isEmpty(form.value.client_name)) {
    ElMessage.error('请输入商家名称');
    return false;
  }
  if (isEmpty(form.value.short_name)) {
    ElMessage.error('请输入商家简称');
    return false;
  }
  if (isEmpty(form.value.belong_country)) {
    ElMessage.error('请选择所属国家');
    return false;
  }
  if (isEmpty(form.value.contacts)) {
    ElMessage.error('请输入联系人');
    return false;
  }
  if (isEmpty(form.value.telephone_prefix)) {
    ElMessage.error('请选择区号');
    return false;
  }
  // if (!telReg1.test(form.value.telephone) && !telReg2.test(form.value.telephone)) {
  //   ElMessage.error('请输入正确的联系电话');
  //   return false;
  // }
  if (isEmpty(form.value.telephone)) {
    ElMessage.error('请输入正确的联系电话');
    return false;
  }
  if (!emailReg.test(form.value.client_email)) {
    ElMessage.error('请输入正确的联系邮箱');
    return false;
  }
  if (isEmpty(form.value.address)) {
    ElMessage.error('请输入联系地址');
    return false;
  }
  if (isEmpty(form.value.user_name)) {
    ElMessage.error('请输入用管理员名称');
    return false;
  }
  if ((isEmpty(form.value.password) || form.value.password.length < 6) && !isEdit.value) {
    ElMessage.error('请输入正确的初始密码');
    return false;
  }
  if (!emailReg.test(form.value.user_email)) {
    ElMessage.error('请输入登录邮箱');
    return false;
  }
  if (isEmpty(form.value.currency_unit)) {
    ElMessage.error('请选择币种');
    return false;
  }
  if (isEmpty(form.value.allow_money) || isNaN(Number(form.value.allow_money))) {
    ElMessage.error('请输入正确的授权金额');
    return false;
  }
  // if (isEmpty(payee_settings.value)) {
  //   ElMessage.error('请添加收款账户');
  //   return false;
  // }
  // if (!payeeRule()) {
  //   return false;
  // }
  return true;
}

const payeeRule = () => {
  let flag = true;
  payee_settings.value.forEach((item, index) => {
    if (isEmpty(item)) {
      ElMessage.error('请添加收款账户');
      flag = false;
      return false;
    }
    console.log(item.provider_id);
    if (!item.provider_id) {
      ElMessage.error('请选择收款账户');
      flag = false;
      return false;
    }
    if (!item.merchant_no) {
      ElMessage.error('请输入商户号');
      flag = false;
      return false;
    }
    if (!item.pos_sn_no) {
      ElMessage.error('请关联POSSN号');
      flag = false;
      return false;
    }
  })
  return flag;
}

const initPayee = () => {
  let list = new Set(payee_settings.value);
  list.forEach((item, index) => {
    if (isEmpty(item)) {
      list.delete(item);
    }
  })
  console.log('list', list);
  payee_settings.value = [...list];
}

const back = () => {
  router.go(-1);
}

const addPayee = () => {
  payee_settings.value.push({})
}

const toAddPOS = (index) => {
  payee_index.value = index;
  addPOSSNRef.value.dialogVisible = true;
  addPOSSNRef.value.textarea = payee_settings.value[index].pos_sn_no;
}

const savePOSVal = (e) => {
  payee_settings.value[payee_index.value].pos_sn_no = e;
  payee_settings.value[payee_index.value].num = e.split(',').length
}

const deletePayee = (index) => {
  if (payee_settings.value.length < 2) {
    return;
  }
  payee_settings.value.splice(index, 1)
}

const toPOSList = async (pos_sn_no) => {
  if (!isEmpty(queryPOSRef.value.posList)) {
    return queryPOSRef.value.dialogVisible = true;
  }
  const Eld = ElLoading.service({ fullscreen: true, text: '加载中...' })
  const res = await getClientDeviceBySn({ pos_sn_no: pos_sn_no });
  Eld.close();
  if (res.code === 1000) {
    queryPOSRef.value.posList = res.data;
    queryPOSRef.value.dialogVisible = true;
  }
}

const getConfig = async () => {
  let merchantConfig = null;
  if (!isEmpty(commonStore.merchantInitConfig)) {
    merchantConfig = commonStore.merchantInitConfig;
  } else {
    const res = await merchantConfigInit();
    if (res.code === 1000) {
      merchantConfig = res.data;
      commonStore.merchantInitConfig = res.data;
    }
  }
  if (isEmpty(merchantConfig)) {
    return;
  }
  countryList.value = merchantConfig.country;
  prefixList.value = merchantConfig.area_code;
  const currency = merchantConfig.currency;
  let newUnitList = [];
  for (let i in currency) {
    newUnitList.push({
      value: i,
      label: currency[i],
      unit_symbol: merchantConfig.currency_symbol[i]
    });
  }
  unitList.value = newUnitList;

}

const queryProvider = async () => {
  const res = await getProvider()
  providerList.value = res.list;
  // console.log(res);
  // if(res.code === 1000){
  //   providerList.value = res.data.list;
  // }
}

const createMerchant = async () => {
  form.value.payee_settings = payee_settings.value;
  const res = await merchantCreated({
    ...form.value
  });
  if (res.code === 1000) {
    ElMessage.success('提交成功');
    disabled.value = true;
    setTimeout(() => {
      router.go(-1)
    }, 1000);
  } else {
    ElMessage.error(res.message);
  }
  isSubmit.value = false;
}

const updateMerchant = async () => {
  form.value.payee_settings = payee_settings.value;
  const res = await merchantUpdated({
    ...form.value,
    client_no: route.query.client_no
  });
  if (res.code === 1000) {
    ElMessage.success('提交成功');
    disabled.value = true;
    setTimeout(() => {
      router.go(-1)
    }, 1000);
  } else {
    ElMessage.error(res.message);
  }
  isSubmit.value = false;
}


// watch

watchEffect(() => {
})

// life
onMounted(async () => {
  if (route.query.client_no) {
    const res = await merchantDetail(route.query.client_no);
    if (res.code === 1000) {
      form.value = { ...res.data, ...res.data.user };
      payee_settings.value = res.data.payee;
    } else {
      ElMessage.error(res.message);
      setTimeout(() => {
        router.go(-1)
      }, 2000);
    }
  }
  getConfig()
  queryProvider();
})


</script>
<style lang="less" scoped>
.add-box {
  margin: 20px;
  width: 80%;
}

.form-title {
  font-weight: bold;
}

.delete-payee {
  margin-left: 10px;
  cursor: pointer;
}

.btn-box {
  margin-top: 50px;
  max-width: 850px;

  :deep(.el-form-item__content) {
    display: flex;
    justify-content: center;
  }
}

.posnum {
  color: var(--el-color-primary);
  cursor: pointer;
  text-decoration: underline;
  padding-right: 10px;
}
</style>